package com.example.component.d_content_provider.custom

import android.content.ContentProvider
import android.content.ContentValues
import android.content.UriMatcher
import android.database.Cursor
import android.net.Uri
import androidx.core.net.toUri

class DatabaseContentProvider : ContentProvider() {

    private val bookDir = 0
    private val bookItem = 1
    private val categoryDir = 2
    private val categoryItem = 3
    private val authority = "com.example.component.provider"
    private var dbHelper: MyDatabaseHelper? = null

    private val uriMatcher by lazy {
        UriMatcher(UriMatcher.NO_MATCH).apply {
            /**
             * 匹配整张表或表中某行
             */
            addURI(authority, "book", bookDir)
            addURI(authority, "book/#", bookItem)
            addURI(authority, "category", categoryDir)
            addURI(authority, "category/#", categoryItem)
        }
    }

    override fun onCreate(): Boolean = context?.let {
        dbHelper = MyDatabaseHelper(it, "BookStore.db", 2)
        true
    } == true

    override fun query(
        uri: Uri,
        projection: Array<out String?>?,
        selection: String?,
        selectionArgs: Array<out String?>?,
        sortOrder: String?
    ): Cursor? = dbHelper?.let {
        val db = it.writableDatabase
        val cursor = when (uriMatcher.match(uri)) {
            bookDir -> {
                db.query("Book", projection, selection, selectionArgs, null, null, sortOrder)
            }

            bookItem -> {
                val bookId = uri.pathSegments[1]
                db.query(
                    "Book",
                    projection,
                    "id = ?",
                    arrayOf(bookId),
                    null,
                    null,
                    null
                )
            }

            categoryDir -> {
                db.query(
                    "Category",
                    projection,
                    selection,
                    selectionArgs,
                    null,
                    null,
                    sortOrder
                )
            }

            categoryItem -> {
                val categoryId = uri.pathSegments[1]
                db.query(
                    "Category",
                    projection,
                    "id = ?",
                    arrayOf(categoryId),
                    null,
                    null,
                    null
                )
            }

            else -> {
                null
            }
        }

        cursor
    }

    override fun getType(uri: Uri): String? = when (uriMatcher.match(uri)) {
        /**
         * 返回指定格式的字符串
         */
        bookDir -> "vnd.android.cursor.dir/vnd.com.example.component.provider.book"
        bookItem -> "vnd.android.cursor.item/vnd.com.example.component.provider.book"
        categoryDir -> "vnd.android.cursor.dir/vnd.com.example.component.provider.category"
        categoryItem -> "vnd.android.cursor.item/vnd.com.example.component.provider.category"
        else -> null
    }

    override fun insert(
        uri: Uri,
        values: ContentValues?
    ): Uri? = dbHelper?.let {
        val db = it.writableDatabase
        val table = when (uriMatcher.match(uri)) {
            bookDir, bookItem -> "book"
            categoryDir, categoryItem -> "category"
            else -> null
        }

        val uri = table?.let {
            val id = db.insert(table, null, values)
            "content://$authority/$table/$id".toUri()
        }
        uri
    }

    override fun delete(
        uri: Uri,
        selection: String?,
        selectionArgs: Array<out String?>?
    ): Int {
        return dbHelper?.let {
            val db = it.writableDatabase
            val deletedRows = when (uriMatcher.match(uri)) {
                bookDir -> {
                    db.delete("book", selection, selectionArgs)
                }

                bookItem -> {
                    val bookId = uri.pathSegments[1]
                    db.delete("book", "id = ?", arrayOf(bookId))
                }

                categoryDir -> {
                    db.delete("category", selection, selectionArgs)
                }

                categoryItem -> {
                    val categoryId = uri.pathSegments[1]
                    db.delete("category", "id = ?", arrayOf(categoryId))
                }

                else -> 0
            }
            deletedRows
        } ?: 0
    }

    override fun update(
        uri: Uri,
        values: ContentValues?,
        selection: String?,
        selectionArgs: Array<out String?>?
    ): Int = dbHelper?.let {
        val db = it.writableDatabase
        val updatedRows = when (uriMatcher.match(uri)) {
            bookDir -> {
                db.update("book", values, selection, selectionArgs)
            }

            bookItem -> {
                val bookId = uri.pathSegments[1]
                db.update("book", values, "id = ?", arrayOf(bookId))
            }

            categoryDir -> {
                db.update("category", values, selection, selectionArgs)
            }

            categoryItem -> {
                val categoryId = uri.pathSegments[1]
                db.update("category", values, "id = ?", arrayOf(categoryId))
            }

            else -> 0
        }
        updatedRows

    } ?: 0
}